import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
import { colors } from '@/constants/colors';
import { CheckIn } from '@/types';

interface CalendarViewProps {
  checkIns: CheckIn[];
  userId: string;
  onCheckIn: (date: string) => void;
  onMakeupCheckIn: (date: string) => void;
}

export const CalendarView: React.FC<CalendarViewProps> = ({
  checkIns,
  userId,
  onCheckIn,
  onMakeupCheckIn,
}) => {
  const [currentMonth, setCurrentMonth] = useState(new Date());
  
  // Get days in month
  const getDaysInMonth = (year: number, month: number) => {
    return new Date(year, month + 1, 0).getDate();
  };
  
  // Get day of week for first day of month (0 = Sunday, 1 = Monday, etc.)
  const getFirstDayOfMonth = (year: number, month: number) => {
    return new Date(year, month, 1).getDay();
  };
  
  // Format date as YYYY-MM-DD
  const formatDate = (year: number, month: number, day: number) => {
    return `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  };
  
  // Check if a date is checked in
  const isCheckedIn = (date: string) => {
    return checkIns.some(checkIn => checkIn.date === date && checkIn.userId === userId);
  };
  
  // Check if a date is a makeup check-in
  const isMakeupCheckIn = (date: string) => {
    return checkIns.some(
      checkIn => checkIn.date === date && checkIn.userId === userId && checkIn.isMakeup
    );
  };
  
  // Check if a date is today
  const isToday = (year: number, month: number, day: number) => {
    const today = new Date();
    return (
      today.getFullYear() === year &&
      today.getMonth() === month &&
      today.getDate() === day
    );
  };
  
  // Check if a date is in the past
  const isPastDate = (year: number, month: number, day: number) => {
    const today = new Date();
    const date = new Date(year, month, day);
    return date < new Date(today.getFullYear(), today.getMonth(), today.getDate());
  };
  
  // Check if a date is in the future
  const isFutureDate = (year: number, month: number, day: number) => {
    const today = new Date();
    const date = new Date(year, month, day);
    return date > new Date(today.getFullYear(), today.getMonth(), today.getDate());
  };
  
  // Navigate to previous month
  const goToPreviousMonth = () => {
    setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1));
  };
  
  // Navigate to next month
  const goToNextMonth = () => {
    setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1));
  };
  
  // Handle day press
  const handleDayPress = (year: number, month: number, day: number) => {
    const date = formatDate(year, month, day);
    
    if (isToday(year, month, day)) {
      // Check in for today
      onCheckIn(date);
    } else if (isPastDate(year, month, day) && !isCheckedIn(date)) {
      // Makeup check-in for past date
      onMakeupCheckIn(date);
    }
    // Do nothing for future dates
  };
  
  // Render calendar
  const renderCalendar = () => {
    const year = currentMonth.getFullYear();
    const month = currentMonth.getMonth();
    const daysInMonth = getDaysInMonth(year, month);
    const firstDayOfMonth = getFirstDayOfMonth(year, month);
    
    const days = [];
    
    // Add empty cells for days before first day of month
    for (let i = 0; i < firstDayOfMonth; i++) {
      days.push(<View key={`empty-${i}`} style={styles.dayCell} />);
    }
    
    // Add days of month
    for (let day = 1; day <= daysInMonth; day++) {
      const date = formatDate(year, month, day);
      const checked = isCheckedIn(date);
      const makeup = isMakeupCheckIn(date);
      const today = isToday(year, month, day);
      const past = isPastDate(year, month, day);
      const future = isFutureDate(year, month, day);
      
      days.push(
        <TouchableOpacity
          key={`day-${day}`}
          style={[
            styles.dayCell,
            today && styles.todayCell,
            checked && styles.checkedCell,
            makeup && styles.makeupCell,
          ]}
          onPress={() => handleDayPress(year, month, day)}
          disabled={checked || future}
        >
          <Text
            style={[
              styles.dayText,
              today && styles.todayText,
              checked && styles.checkedText,
              past && !checked && styles.pastText,
              future && styles.futureText,
            ]}
          >
            {day}
          </Text>
        </TouchableOpacity>
      );
    }
    
    return days;
  };
  
  // Get month name
  const getMonthName = (month: number) => {
    const monthNames = [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ];
    return monthNames[month];
  };
  
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={goToPreviousMonth}>
          <Text style={styles.navButton}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.monthTitle}>
          {getMonthName(currentMonth.getMonth())} {currentMonth.getFullYear()}
        </Text>
        <TouchableOpacity onPress={goToNextMonth}>
          <Text style={styles.navButton}>{'>'}</Text>
        </TouchableOpacity>
      </View>
      
      <View style={styles.weekdayHeader}>
        {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(day => (
          <Text key={day} style={styles.weekdayText}>{day}</Text>
        ))}
      </View>
      
      <View style={styles.calendarGrid}>
        {renderCalendar()}
      </View>
      
      <View style={styles.legend}>
        <View style={styles.legendItem}>
          <View style={[styles.legendDot, styles.checkedDot]} />
          <Text style={styles.legendText}>Checked In</Text>
        </View>
        <View style={styles.legendItem}>
          <View style={[styles.legendDot, styles.makeupDot]} />
          <Text style={styles.legendText}>Make-up</Text>
        </View>
        <View style={styles.legendItem}>
          <View style={[styles.legendDot, styles.todayDot]} />
          <Text style={styles.legendText}>Today</Text>
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: colors.background,
    borderRadius: 16,
    padding: 16,
    marginVertical: 8,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 16,
  },
  navButton: {
    fontSize: 24,
    color: colors.primary,
    paddingHorizontal: 8,
  },
  monthTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text.primary,
  },
  weekdayHeader: {
    flexDirection: 'row',
    marginBottom: 8,
  },
  weekdayText: {
    flex: 1,
    textAlign: 'center',
    color: colors.text.secondary,
    fontWeight: '500',
    fontSize: 14,
  },
  calendarGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  dayCell: {
    width: '14.28%', // 100% / 7 days
    aspectRatio: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginVertical: 2,
  },
  dayText: {
    fontSize: 16,
    color: colors.text.primary,
  },
  todayCell: {
    backgroundColor: colors.primary + '20',
    borderRadius: 999,
  },
  todayText: {
    color: colors.primary,
    fontWeight: '600',
  },
  checkedCell: {
    backgroundColor: colors.success + '30',
    borderRadius: 999,
  },
  checkedText: {
    color: colors.success,
    fontWeight: '600',
  },
  makeupCell: {
    backgroundColor: colors.secondary + '30',
    borderRadius: 999,
  },
  pastText: {
    color: colors.text.tertiary,
  },
  futureText: {
    color: colors.text.tertiary,
  },
  legend: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 16,
    paddingTop: 16,
    borderTopWidth: 1,
    borderTopColor: colors.border,
  },
  legendItem: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  legendDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
    marginRight: 8,
  },
  legendText: {
    fontSize: 12,
    color: colors.text.secondary,
  },
  checkedDot: {
    backgroundColor: colors.success + '30',
  },
  makeupDot: {
    backgroundColor: colors.secondary + '30',
  },
  todayDot: {
    backgroundColor: colors.primary + '20',
  },
});